var table = null;
var id_key = null;
var tableConfig = {
		isEdit : true,
		isDel : true,
		isAdd :  true
};
// initTable();
$(document).ready(function(){
		if(config != null){
			config.tableName="${tableName}";
		}else{
			config = {
					tableName:"${tableName}"		
			}
		}
		parseData();
		parseConfig();
		addBtn();
		addToorBar();
		reload();
		$(".fixed-table-loading").hide();
});

function reload(flag){
	table = $('#table').bootstrapTable("destroy");
	initTable(flag);
}

function addBtn(){
	var  btns = window["btns"]
	if(btns && btns.length>0){
		for(var i =0;i<btns.length;i++){
			var btn = btns[i];
			$("#btns").append(btn);
		}
	}
}

function addToorBar(){
	var toolBars = config["toolBar"];
	if(toolBars){
		var len = toolBars.length;
		if(len>0){
			$("#searchBtn").show();
		}
		for(var i =0;i<len;i++){
			var toolBar = toolBars[i];
			var type = toolBar.type;
			var value = toolBar.value;
			var html = "";
			if(type == "select"){
				var optStr ="";
				for(var j =0;j<value.length;j++){
					optStr +=' <option value="'+value[j].value+'">'+value[j].title+'</option>';
				}
				 html = '<div><label class="col-sm-1 control-label">'+toolBar.title+'：</label>\
					                                <div class="col-sm-2">\
					                                  	<select name="'+toolBar.key+'" class="form-control tableToolBar" >'+optStr+'</select>\
					                						 </div> \
					              				</div>'
			}
			if(type == "input"){
				 html = '<div><label class="col-sm-1 control-label">'+toolBar.title+'：</label>\
					                                <div class="col-sm-2">\
					                                  	<input name="'+toolBar.key+'" class="form-control tableToolBar" />\
					                						 </div> \
					              				</div>'
			}
			
			$("#condition").append($(html));
		}
	}
}
function parseData(){
	parseTableCol();
}
function parseConfig(){
	if(config.isEdit == false){
		tableConfig.isEdit = false;
	}
	if(config.isAdd == false){
		tableConfig.isAdd = false;
		$("#table_add_btn").hide();
	}
	if(config.isDel == false){
		tableConfig.isDel = false;
	}
}
var tableCol = [];
var tableColMap = {};
function parseTableCol(){
	if(tableCol == null){
		tableCol = [];
	}
	var len = dataFormat.length;
	var n = 0;
	for(var i =0;i<len;i++){
		var attr = dataFormat[i];
		if(attr.pk){
			id_key = attr.field;
		}
		var isShow = true;
		if(attr.show == false){
			isShow = false;
		}
		if(isShow){
			tableCol.push(attr);
		}
		if(attr.dataType == "dict"){
			var dict = attr.dict;
			if(!attr.formatter){
				n += 1
				attr.formatter = function(value,data){
					return dict[value];
				}
			}
		}
		if(attr.dataType == "bigstring"){
			if(!attr.formatter){
				attr.formatter = function(value,data){
					if(!value){
						return "";
					}
					var div = "";
					var values = value.split("\r\n");
					for(var j = 0;j<values.length;j++){
						div+="<div>"+values[j]+"</div>";
					}
					return div;
				}
			}
		}
		if(attr.dataType == "file"){
			if(!attr.formatter){
				attr.formatter = function(value,data){
					if(value == null){
						return "";
					}
					var files = value.split(",");
					var div = "";
					for(var j = 0;j<files.length;j++){
						var img = files[j];
						var index= img.lastIndexOf(".");
						var ext = img.substr(index+1);
						var path = imgLocation+img;
						if(isAssetTypeAnImage(ext)){
							div+='<div  style="display:inline-block;margin:10px"><div style="display:inline-block"><img class="element" style="width:50px;height:50px" onclick="return showImg(this)" name="'+img+'" src="'+path+'"/></div></div>';
						}else{
							div+='<div  style="display:inline-block;margin:10px"><div style="display:inline-block"><a class="element" target="_blank"  name="'+img+'" href="'+path+'">'+img+'</a></div></div>';

						}
					}
					return div;
				}
			}
		}
		tableColMap[attr.field] = attr;
	}
}

function parseEditData(data){
	var html = "";
	var len = dataFormat.length;
	for(var i =0;i<len;i++){
		var attr = dataFormat[i];
		var edit = true;
		if(attr.edit == false){
			edit = false;
		}
		if(edit){
			var curHTML = getRenderHtml(attr,data);
			html +=curHTML;	
		}
	}
	return html;
}


function initTable(flag){
	var index = 1;
	if(!flag){
		var cols = window["extraCol"];
		if(!cols){
    		cols = config.extraCol;
    	}
		if(tableConfig.isEdit || tableConfig.isDel || cols){
			tableCol.push({
				 title: '操作',
			     align: 'center',
			     width:"15%",
			    formatter:function(value,data,index){
			    	var html = "";
			    	if(tableConfig.isEdit){
			    		html += '<button class="btn btn-success" onclick="edit(\''+data.id+'\',\''+index+'\')"><i class="fa fa-edit"></i>修改</button>'
			    	}
			    	if(tableConfig.isDel){
			    		html += '<button style="margin-left:5px" class="btn btn-danger" onclick="del(\''+data.id+'\',\''+index+'\')"><i class="fa fa-trash"></i>删除</button>'
			    	}
			    	
			    	if(cols){
			    		for(var i =0;i<cols.length;i++){
			    			var col = cols[i];
			    			html +=col(value,data,index);
			    		}
			    	}
			    	return html;
			    }
		});
		}
	}
	

	var pageSize = 100;
	if(!window["pageConfig"]){
		window["pageConfig"] = {};
	}else{
		pageSize = window["pageConfig"]["pageSize"] ||100
	}
	var serverDataUrl = "./query";
	if(window["dataUrl"]){
		serverDataUrl = window["dataUrl"];
	}
	table = $('#table').bootstrapTable({
		onLoadSuccess:function(){
			if(config["afterInit"]){
				config["afterInit"]();
			}
		},
        method: 'get',
        sortable : true,
        toolbar: '#toolbar',    //工具按钮用哪个容器
        striped: true,      //是否显示行间隔色
        cache: false,      //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,     //是否显示分页（*）
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: pageSize,      //每页的记录行数（*）
        pageList: [10, 25, 50, 100],  //可供选择的每页的行数（*）
        url: serverDataUrl,//这个接口需要处理bootstrap table传递的固定参数
        queryParamsType:'', //默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
                            // 设置为 ''  在这种情况下传给服务器的参数为：pageSize,pageNumber

        queryParams: queryParams,//前端调用服务时，会默认传递上边提到的参数，如果需要添加自定义参数，可以自定义一个函数返回请求参数
        sidePagination: "server",   //分页方式：client客户端分页，server服务端分页（*）
        search: false,      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: false,
        //showColumns: true,     //是否显示所有的列
//         showRefresh: true,     //是否显示刷新按钮
        minimumCountColumns: 2,    //最少允许的列数
        clickToSelect: true,    //是否启用点击选中行
        searchOnEnterKey: true,
        idField : "id",
        columns: tableCol,
        uniqueId:id_key
    });
}

function showImg(img){
	$('#window-img').empty();
	var img = "<img class='window-img' src='" + img.src + "' width='100%' />";
	$('#window-img').append(img);
	layer.open({
		type: 1,
		title: false,
		//resize:false,
		shadeClose: true, //点击遮罩关闭
		content: $('#window-img'),
		area: 'auto',
		maxWidth: 400,
		cancel: function() {
			$('#window-img').css('display', 'none');
		},
		end: function() {
			$('#window-img').css('display', 'none');
		}
	});
return false;
}

function showImgByWidth(img,area){
	$('#window-img').empty();
	var img = "<img class='window-img' src='" + img.src + "' width='100%' />";
	$('#window-img').append(img);
	layer.open({
		type: 1,
		title: false,
		//resize:false,
		shadeClose: true, //点击遮罩关闭
		content: $('#window-img'),
		area: ["800px","600px"],
		cancel: function() {
			$('#window-img').css('display', 'none');
		},
		end: function() {
			$('#window-img').css('display', 'none');
		}
	});
return false;
}
function queryParams(param){
	param["key"]=config["tableName"];
	
	if(config["order"]){
		param["order"]=config["order"];
	}
	if(config["extraParam"]){
		var extraParam = config["extraParam"];
		for(var key in extraParam){
			param[key]=extraParam[key];
		}
	}
	var tableToolBars = $(".tableToolBar");
	var toolBarList = [];
	for(var i =0;i<tableToolBars.length;i++){
		var tableToolBar = tableToolBars[i];
		var type = tableToolBar.tagName.toLowerCase();
		var name = $(tableToolBar).attr("name")
		if(type == "input"){
			toolBarList.push({
				type:"input",
				key:name
			})
		}else if(type == "select"){
			toolBarList.push({
				type:"select",
				key:name
			})
		}
	
		var value = $(tableToolBar).val();
		param[name] = value;
	}
	if(tableToolBars.length){
		param["toolBarConfig"] = JSON.stringify(toolBarList)
	}
	return param;
}
function add(){
	let area = ['600px', '500px'];
	var html = parseEditData({});
	  layer.open({
        type: 1,
        title: '新增',
        btn:["确定","取消"],
        area: area,
        shadeClose: true, //点击遮罩关闭
        content:'<div class="ibox-content form-horizontal"><form id="newForm" class="form-horizontal"  method="post">\
          	'+html+'\
         </form>\
        </div>',
        yes:function(){
      	  var arry = $("#newForm").serializeArray();
          var msg = doCheck(arry);
          if(msg){
        	  layer.msg(msg);
        	  return;
          }
      	  var obj = {};
      	  for(var i=0;i<arry.length;i++){
      		  var cur = arry[i];
      		  obj[cur.name] = cur.value;
      	  }
      	  obj["key"] = config["tableName"];
      	  var url = "./save";
      	  if(window["saveUrl"]){
      		  url = window["saveUrl"];
      	  }
      	if(id_key){
    		obj["pri_key"]=id_key
    	}
      	if(config["beforeAdd"]){
		  config["beforeAdd"](obj);
      	}
      	  sendReq({
      		  url:url,
      		  data:obj,
      		  success:function(res){
      			  layer.closeAll();
      			  if(res.status){
      				  $('#table').bootstrapTable("refresh")
      				  layer.msg("添加成功");
      			  }else{
      				  layer.msg(res.msg)
      			  }
      		  }
      	  });
        }
    });
	 setTimeout(function(){
		 bindDateEvent();
	 }, 500);
}

function doCheck(array){
	var len = array.length;
	for(var i =0 ;i<len;i++){
		var dataObj = array[i];
		var field = dataObj.name;
		var value = dataObj.value;
		var colData = tableColMap[field];
		if(colData.isNull == false){
			if(value == null || value == ""){
				return colData.title  +"不能为空";
			}
		}
		
	}
	return null;
}

function edit(id,index){
	
	layer.load();
	var url = "./getById?id="+id;
	if(window["idUrl"]){
		url = window["idUrl"]+"?id="+id;
	}
	if(id_key){
		url = url+"&pri_key="+id_key;
	}
	var obj = {};
	obj["key"] = config["tableName"];
	
	sendReq({
		url:url,
		data:obj,
		success:function(data){
			layer.closeAll();
			var html = parseEditData(data);
			layer.open({
		          type: 1,
		          title: '修改',
		          btn:["确定","取消"],
		          area: ['600px', '500px'],
		          shadeClose: true, //点击遮罩关闭
		          content:'<div class="ibox-content form-horizontal"><form id="editForm" class="form-horizontal"  method="post">\
		            	'+html+'\
		           </form>\
		          </div>',
		          yes:function(){
		        	  var arry = $("#editForm").serializeArray();
		        	   var msg = doCheck(arry);
		               if(msg){
		             	  layer.msg(msg);
		             	  return;
		               }
		        	  var obj = {};
		        	  for(var i=0;i<arry.length;i++){
		        		  var cur = arry[i];
		        		  obj[cur.name] = cur.value;
		        	  }
		        	  var url = "./edit";
		        	  if(window["editUrl"]){
		        		  url = window["editUrl"];
		        	  }
		        	  if(id_key != null){
		        	  	obj[id_key] = data[id_key];
		        	  	url = url+"?pri_key="+id_key;
		        	  }
		        	  obj["key"] = config["tableName"];
		        	  if(!id_key){
		        			obj["id"] = id;
		        	  }
	        	   		if(config["beforeEdit"]){
	        			  config["beforeEdit"](obj);
	        	      	}
		        	  sendReq({
		        		  url:url,
		        		  data:obj,
		        		  success:function(res){
		        			  layer.closeAll();
		        			  if(res.status){
		        				  $('#table').bootstrapTable("updateRow",{index:index,row:res.data})
		        				  layer.msg("修改成功");
		        			  }else{
		        				  layer.msg(res.msg)
		        			  }
		        		  }
		        	  });
		          },
		      });
			  bindDateEvent();
		}
	});
	
}
function bindDateEvent(){
	var doms = $(".datepicker");
	for(let i =0;i<doms.length;i++){
		let dom = doms[i];
		let id = dom.id;
		console.log(id);
		let end = {
				elem : '#'+id,
				format : 'YYYY-MM-DD hh:mm:ss',
				istime : true,
				istoday : true,
			};
			laydate(end);
	}
}

function sendReq(opt){
	var extraParam = config["extraParam"];
	if(extraParam){
		for(var key in extraParam){
			opt.data[key]=extraParam[key];
		}
	}
	$.ajax(opt);
}
function del(id,index){
	layer.confirm('您确定要删除该条记录？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			var url = "./del?id="+id;
			 if(id_key != null){
	        	  	url = url+"&pri_key="+id_key;
	        	  }
			 var obj = {};
			 obj["key"]=config["tableName"];
			sendReq({
		 		url:url,
		 		data:obj,
		 				dataType:"json",
		 				success:function(e){
		 					layer.closeAll();
		 					if(e.status){
	        				  $('#table').bootstrapTable("removeByUniqueId",id)
		 					}
		 				}
		 	});
		}, function(){
		  
		});
}
function getTableData(index){
	var datas = $('#table').bootstrapTable("getData");
	return datas[index];
}

function uploadFile(){
        $.ajaxFileUpload(
            {
                url: ctx+'/user/uploadFile', //用于文件上传的服务器端请求地址
                secureuri: false, //是否需要安全协议，一般设置为false
                fileElementId: 'uploadFile', //文件上传域的ID
                success: function (data, status)  //服务器成功响应处理函数
                {
                	var res = JSON.parse(data.body.innerText);
                	$("#uploadFile").val("");
                	handelerResult(res)
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                   debugger;
                }
            }
        );
        return false;
}
function readUploadFile(obj){
	uploadFile();
}


function search(){
	reload(true);
}